<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="新增策略" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form"
  import { addFormSchemas } from "./data"
  import * as permPolicyApi from '/@/api/iam/permPolicy';
  import { NamespaceCodeEnum } from '/@/enums/iamEnum'

  const apiNamespaceCode = ref('')
  const emit = defineEmits(["register", "success"])
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: addFormSchemas,
    labelWidth: 80,
    wrapperCol: { lg: 24, md: 24 },
    showActionButtonGroup: false,
  })
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    apiNamespaceCode.value = data.apiNamespaceCode
    const showPolicyType = data.apiNamespaceCode == NamespaceCodeEnum.APP_MGT ? false : data.showPolicyType
    setModalProps({ confirmLoading: false, minHeight: 80 })
    setFieldsValue({ showPolicyType, apiNamespaceCode: apiNamespaceCode.value })
  })
  async function handleSubmit() {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      await permPolicyApi.savePermissionPolicy({ ...values, apiNamespaceCode: apiNamespaceCode.value  })
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
